from multiprocessing import Process
import time
from libs.conn import *
import os

# 判断当前系统环境是windows还是linux，同时判断是32为还是64位
def get_os():
    if os.name == 'nt': # windows系统
        # 判断是32位还是64位
        if 'PROGRAMFILES(X86)' in os.environ:
            return 'windows_64'
        else:
            return 'windows_32'
    else: # linux系统
        return 'linux'

def is_port_in_use(port):
    import socket
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        return s.connect_ex(('localhost', port)) == 0

# 开启iperf3服务
def start_iperf3_service():
    # 获取iperf3端口配置
    iperf3_port = int(get_config('cmd_iperf3_server_port'))
    # 检测端口是否已经被占用，如果被占用则跳过
    if is_port_in_use(iperf3_port):
        print(f"端口 {iperf3_port} 已经被占用，跳过开启iperf3服务")
        return
    if 'windows' in get_os():
        if get_os() == 'windows_64':
            iperf3_path = ".\\tools\\iperf3\\iperf-3.1.3-win64\\iperf3.exe"
            cmd = f"{iperf3_path} -s -p {iperf3_port} -D"
        else:
            iperf3_path = ".\\tools\\iperf3\\iperf-3.1.3-win32\\iperf3.exe"
            cmd = f"{iperf3_path} -s -p {iperf3_port} -D"
    else:
        cmd = f"iperf3 -s -p {iperf3_port} -D"
    os.system(cmd)
    if is_port_in_use(iperf3_port):
        print(f"iperf3服务启动成功，端口：{iperf3_port}")
    else:
        print(f"iperf3服务启动失败，端口：{iperf3_port}")

def stop_iperf3_service():
    if 'windows' in get_os():
        # -D参数表示后台运行，-p参数指定端口号
        cmd = f"taskkill /f /im iperf3.exe"
    else:
        cmd = f"kill -9 $(lsof -t -i:{iperf3_port})"
    # 关闭iperf3服务，检测ipref3字样的进程，然后kill掉
    # cmd = f"ps -ef | grep iperf3 | grep -v grep | awk '{{print $2}}' | xargs kill -9"
    # cmd = f"kill -9 $(lsof -t -i:{iperf3_port})"
    os.system(cmd)
    

def check_iperf3_service():
    # 检测间隔
    check_interval = 60
    while True:
        print("开始检测ipref3服务是否启动")
        try:
            # 检测是否设置开启ipref3服务
            if get_config('cmd_iperf3_server_enable') == '0':
                print("ipref3服务未开启，跳过检测")
                time.sleep(check_interval)
                continue
            # 开启iperf3服务
            start_iperf3_service()

        except Exception as e:
            print(f"Error: {e}")

        time.sleep(check_interval)


def check_iperf3_service_process():
    p = Process(target=check_iperf3_service)
    #p.daemon = True # 设置为守护进程，如果主进程退出，子进程也会退出
    p.start()
    return p.pid